import React,{Component} from 'react';
import './login.css';

import qs from 'qs';
import {Link} from 'react-router-dom'

import HdbNav from '../../components/hdb-input';
import HdbInput from '../../components/hdb-input';
import HdbButton from '../../components/hdb-button'
import {queryLogin} from "../../services/user";

//1 结构  使用通用组件
//2 样式
//3 数据交互
//4. 同步local

export default class Login extends Component{

    state = {
        username:'',
        password:'',
        errorMess:'',//登录失败时的信息
    };

    //通过onChange事件 修改 model值， 反向数据流
    changeIpt = (ev) => {
        this.setState({
            [ev.target.name]:ev.target.value
        })
    };

    //登录 数据交互 同步local

    login = async () => {

        let {username,password}=this.state;
        let res = await queryLogin({username,password});

        if (res.data.err===0){
            //同步local  明文
            window.localStorage.setItem('user',qs.stringify(res.data))

            //跳转

            //获取跳转路径
            let path = qs.parse(this.props.location.search,{ignoreQueryPrefix: true}).path;
            // console.log('login',path);

            if (path && !path.includes('/login')) {
                //跳转到之前
                this.props.history.push(path)
            } else {
                //跳转到用户中心  user
                this.props.history.push('/user')
            }



        } else {
            this.setState({errorMess:res.data.msg})
        }

    };


    render(){
        let {username,password,errorMess} = this.state;
        return (
            <div className="content">
                <HdbNav arrow="gray" bgColor="transparent" borderWidth={0} />
                <h1></h1>
                <div className="login-box">
                    <p className="lsolid"></p>
                    <div className="login">
                        <Link to="/login">登录</Link>
                        <span></span>
                        <Link to="/reg">注册</Link>
                    </div>
                    <p className="rsolid"></p>
                </div>
                <ul>
                    <HdbInput
                        label={"用户"}
                        model={{name:'username',value:username,onChange:this.changeIpt}}
                    />
                    <HdbInput
                        label={"密码"}
                        type={"password"}
                        model={{name:'password',value:password,onChange:this.changeIpt}}
                    />
                    <span style={{color:'red'}}>{errorMess}</span>
                </ul>
                <div className="footbox">
                    <HdbButton
                        style={{marginTop:'.64rem'}}
                        onClick={this.login}
                        size="large"
                    >登录录</HdbButton>
                    <a  className="tishi">忘记密码？</a>
                </div>
            </div>
        )
    }
}